package com.weayer.service;

import com.weayer.constant.CommonStatusEnum;
import com.weayer.constant.DriverConstants;
import com.weayer.constant.IdentityConstants;
import com.weayer.constant.TokenConstants;
import com.weayer.dto.ResponseResult;
import com.weayer.remote.ServiceDriverClient;
import com.weayer.remote.ServiceVerificationcodeClient;
import com.weayer.response.DriverUserResponse;
import com.weayer.response.NumberCodeResponse;
import com.weayer.response.TokenResponse;
import com.weayer.util.JwtUtils;
import com.weayer.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @description:  Api服务 - 司机 - 验证码service
 * @author: Weayer
 **/
@Service
@Slf4j
public class VerificationCodeService {
    @Autowired
    private ServiceDriverClient serviceDriverClient;
    @Autowired
    private ServiceVerificationcodeClient serviceVerificationcodeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @Description: 生成司机验证码
     * @Param: [driverPhone]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult generatorCode(String driverPhone){
        // 查询该手机号的司机是否存在
        ResponseResult<DriverUserResponse> response = serviceDriverClient.checkDriver(driverPhone);
        DriverUserResponse data = response.getData();
        int ifExists = data.getIfExists();
//        log.info(String.valueOf(ifExists));
        if(ifExists == DriverConstants.DRIVER_USER_NOT_EXISTS){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXISTS.getCode(), CommonStatusEnum.DRIVER_NOT_EXISTS.getValue());
        }
        // 调用验证码服务，获取6位验证码
        ResponseResult<NumberCodeResponse> numberCodeResponseResult = serviceVerificationcodeClient.getNumberCode(6);
        int numberCode = numberCodeResponseResult.getData().getNumberCode();
        // key, value 存入redis
        String key = RedisPrefixUtils.generatorKeyByPhone(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        stringRedisTemplate.opsForValue().set(key, numberCode+"", 2, TimeUnit.MINUTES);
        // 通过短信服务商将验证码发送

//        JSONObject result = new JSONObject();
//        result.put("code", 1);
//        result.put("message", "success");
//        result.put("data", numberCode);

        return ResponseResult.success(numberCode);
    }

    /**
     * @Description: 司机验证码校验
     * @Param: [driverPhone, verificationCode]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult checkCode(String driverPhone, String verificationCode){
        // 根据手机号，redis中读取验证码
            // 1. 生成key 2. 获取value
        String key = RedisPrefixUtils.generatorKeyByPhone(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        String codeRedis = stringRedisTemplate.opsForValue().get(key);

        // 验证码校验
        if(StringUtils.isBlank(codeRedis)){
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_INVALID.getCode(), CommonStatusEnum.VERIFICATION_CODE_INVALID.getValue());
        }
        if(!codeRedis.trim().equals(verificationCode.trim())){
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }

        // 生成2个 token 令牌
        String accessToken = JwtUtils.generatorToken(driverPhone, IdentityConstants.DRIVER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(driverPhone, IdentityConstants.DRIVER_IDENTITY, TokenConstants.REFRESH_TOKEN_TYPE);

        // 生成两个 tokenKey，然后存到redis 中
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(driverPhone, IdentityConstants.DRIVER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(driverPhone, IdentityConstants.DRIVER_IDENTITY, TokenConstants.REFRESH_TOKEN_TYPE);
//        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
//        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 10, TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 60, TimeUnit.SECONDS);

        // 响应
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
